package net.zhengxinyun.performance.App.appCtrl;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.App.service.cityIndex.CityIndexService;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.HistoryScoreDTO;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.service.incentive.IncentiveService;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryUnitScoreService;
import net.zhengxinyun.performance.service.indicators.TownScoreService;
import net.zhengxinyun.performance.service.workSupervision.WorkScoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/depart")
public class DepartScoreCtrl extends BaseCtrl {

    @Autowired
    private TownScoreService townScoreService;// 县对乡考核分数 service

    @Autowired
    private CountryIndicatorsService cityIndexService; // 市对县指标Web service

    @Autowired
    private CityIndexService appcityIndexService;

    @Autowired
    private CountryUnitScoreService countryUnitScoreService;


    @Autowired
    private IncentiveService incentiveService;// 正向激励web service

    @Autowired
    private WorkScoreService workScoreService;// 工作督查service

    //县直单位或乡镇首页得分情况
    @PostMapping("/totalScore")
    public Result<HashMap<String,Object>> cityIndexDetails(@RequestBody IndexUserDTO dto)
    {

        String currentYear = getCurrentYear();
        UserFilter userInfo = getUserInfo(dto.getUserPhone());
        String departcode = userInfo.getDepartcode();
        String departType = userInfo.getDepartType();


        HashMap<String,Object> dataMap = new HashMap<>();

        switch (departType){
            case "乡镇":
                TownIndicatorsFilter townFilter = new TownIndicatorsFilter();

                townFilter.setDepartCode(departcode);
                townFilter.setDateTime(DateUtils.getLastMonth(currentYear));
                townFilter.setIndexYear(currentYear);

                List<TownIndicatorsFilter> indictScore = townScoreService.getIndictScore(townFilter);
                //过滤未填报的指标
                indictScore = indictScore.stream().filter(filter -> StringUtils.isNotBlank(filter.getFinalScore())  ).collect(Collectors.toList());

                double sumfinalScore = indictScore.stream().mapToDouble(TownIndicatorsFilter::getDoubleFinaScore).sum();
                int sumWeight = indictScore.stream().mapToInt(TownIndicatorsFilter::getIntWeight).sum();

                double townrate = sumfinalScore/sumWeight*100;


              //  double indexSum = indictScore.stream().mapToDouble(TownIndicatorsFilter::getDoubleFinaScore).sum();
                dataMap.put("indexScore",DataUtil.formatNumberDouble(3,townrate)); //指标得分率
                break;

            case "县直单位":
                CountryIndicatorsFilter indexFilter = new CountryIndicatorsFilter();
                indexFilter.setIndexType("二级指标");
                indexFilter.setLeadUnit(dto.getDepartcode());
                // 设置日期， 这个日期有点奇葩啊；干
                if (StringUtils.isBlank(dto.getDateTime())) {
                    indexFilter.setMonthTime(DateUtils.getLastMonth(currentYear));
                    indexFilter.setDateTime(currentYear);
                }
                UserEntity userEntity = new UserEntity();
                BeanUtils.copyProperties(userInfo, userEntity);

                List<CountryIndicatorsFilter> listIndesScore = cityIndexService.querySecondIndex(indexFilter, userEntity);
                listIndesScore = listIndesScore.stream().filter(filter -> "1".equals(filter.getAudit())).collect(Collectors.toList());//过滤已填报的
                double cityindexSum = listIndesScore.stream().mapToDouble(CountryIndicatorsFilter::getFinalScoreNotNull).sum();
                int weightsum = listIndesScore.stream().mapToInt(CountryIndicatorsFilter::getWeight).sum();
                double rate =(cityindexSum/weightsum)*100;
                if(Double.isNaN(rate)){
                    rate=0;
                }
                dataMap.put("indexScore", DataUtil.formatNumberDouble(2,rate)); //指标得分率
                break;
                default:
                    dataMap.put("indexScore","-"); //指标得分率
                    break;
        }


        //  正向激励
        IncentiveFilter dtofilter = new IncentiveFilter();
        dtofilter.setAudit("1");
        dtofilter.setDateTime(currentYear);
        dtofilter.setDepartCode(departcode);
        List<IncentiveFilter> listincet = incentiveService.queryAll(dtofilter);
        double sumIncent = listincet.stream().mapToDouble(IncentiveFilter::getDoublePoint).sum();
        sumIncent = Util.keepNumberFormat(2,sumIncent);

        // 专项工作督查
        WorkScoreFilter workFilter = new WorkScoreFilter();
        workFilter.setYear(currentYear);
        workFilter.setDepartCode(departcode);
        List<WorkScoreFilter> query = workScoreService.query(workFilter);
        double sumWroks = query.stream().mapToDouble(WorkScoreFilter::getDouleFinalScore  ).sum();
        dataMap.put("rank","-");
        dataMap.put("currentScore","-");
        dataMap.put("SpecialWorkScore",-sumWroks); // 专项工作督查
        dataMap.put("insprireScore",sumIncent); // 正想激励
        dataMap.put("VisitCheckScore","-"); // 察访核验
        dataMap.put("publicTest","-");// 公众评议

        System.out.println("/totalScore");
        return ResultUtils.getSuccessResults(dataMap);
    }


    //获取指标得分的历史记录
    @RequestMapping("/getindexHistory")
    public Result<HashMap<String, Object>> getHistoryData(@RequestBody IndexUserDTO param)
    {

        String indexClass = param.getIndexClass();
        Long indexId = param.getIndexId();
        if(StringUtils.isBlank(indexClass)|| ObjectUtils.isBlank(indexId))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "indexClass或者 indexid不能为空",null);
        }
        HashMap<String,Object> datamap = new HashMap<>();
        String currentYear = getCurrentYear();

        switch (indexClass)
        {

            case "1":

                List<ScoreDTO> yearCityIndex1 = appcityIndexService.getYearCityIndex(indexId, currentYear);
                datamap.put("data",yearCityIndex1);

                break;



            case "2":

                List<HistoryScoreDTO> list = townScoreService.TownHistoryData(indexId);
                datamap.put("data",list);
                break;

            case "3":

                String[] month = Util.MONTH;
                CountryUnitScoreFilter departFilter = new CountryUnitScoreFilter();
                departFilter.setIndexId(indexId+"");
                List<HashMap<String, Object>> hashMaps = countryUnitScoreService.queryAllData(departFilter);
                for (HashMap<String, Object> hashMap : hashMaps) {

                    String mon ="month";
                    for (String str : month) {

                        Object obj = hashMap.get(mon + str);
                        if(ObjectUtils.isBlank(obj))
                        {
                            hashMap.put(mon+str,null);
                        }

                    }

                }



                datamap.put("data",hashMaps);

                break;



        }


        return ResultUtils.getSuccessResults(datamap);

    }




}
